package com.css.fxfzdzzh.modules.evaluate.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.common.utils.CheckObjFields;
import com.css.fxfzdzzh.constants.YNEnum;
import com.css.fxfzdzzh.enums.DisasterTypeEnum;
import com.css.fxfzdzzh.enums.ResultEnum;
import com.css.fxfzdzzh.enums.TaskEnum;
import com.css.fxfzdzzh.modules.drill.service.DrillService;
import com.css.fxfzdzzh.modules.eqLandslide.count.entity.DzzhCountAreaResult;
import com.css.fxfzdzzh.modules.eqLandslide.count.entity.DzzhResultLogisticGrowth;
import com.css.fxfzdzzh.modules.eqLandslide.count.service.EqLandslideService;
import com.css.fxfzdzzh.modules.eqLandslide.count.vo.TaskModelLogiGrowthVO;
import com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.repository.LawAnalysisRepository;
import com.css.fxfzdzzh.modules.evaluate.VO.EvaluateVO;
import com.css.fxfzdzzh.modules.evaluate.VO.PolygonEvaluateResultVO;
import com.css.fxfzdzzh.modules.evaluate.VO.SoftSoilQueryVO;
import com.css.fxfzdzzh.modules.evaluate.entity.*;
import com.css.fxfzdzzh.modules.evaluate.repository.SoftSoilRepository;
import com.css.fxfzdzzh.modules.evaluate.service.SoftSoilService;
import com.css.fxfzdzzh.modules.taskManage.entity.TaskEntity;
import com.css.fxfzdzzh.modules.taskManage.repository.TaskRepository;
import com.css.fxfzdzzh.modules.taskManage.vo.TaskQueryVO;
import com.css.fxfzdzzh.modules.tifData.service.ElevationMapService;
import com.css.fxfzdzzh.util.CreateGson;
import com.css.fxfzdzzh.util.PlatformObjectUtils;
import com.css.fxfzdzzh.util.UUIDGenerator;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.zcpt.sys.entity.SUser;
import com.css.fxfzdzzh.zcpt.sys.service.SUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Dbj
 * @date 2023年02月14日  15:11
 */
@Service
public class SoftSoilServiceImpl implements SoftSoilService {

    @Resource
    private SoftSoilRepository softSoilRepository;

    @Resource
    LawAnalysisRepository lawAnalysisRepository;

    @Resource
    SUserService sUserService;

    @Resource
    DrillService drillService;

    @Value("${basicData.url}")
    public String basicDataUrl;
    @Resource
    TaskRepository taskRepository;
    @Resource
    EqLandslideService eqLandslideService;
    @Resource
    ElevationMapService elevationMapService;
    @Resource
    JdbcTemplate jdbcTemplate;

    @Override
    public Map<String, Object> getPage(SoftSoilQueryVO vo, int curPage, int pageSize) {
        String userId = PlatformSessionContext.getUserID();
        vo.setCreateUser(userId);
        Map<String, Object> task = softSoilRepository.findTask(vo, curPage, pageSize);
//        List<TaskEntity> tasks = (List<TaskEntity>) task.get("rows");
//        Map<String,Object> statusMap = getStatusMap();
//        Map<String,Object> typeMap = getDisasterType();
//        for(TaskEntity entity:tasks){
//            entity.setDisasterType(DisasterTypeEnum.SUBSIDENCE.getDesc());
//            //评估状态
//            String evaluateItem = entity.getEvaluateItem();
//            if(evaluateItem.contains(DisasterTypeEnum.SUBSIDENCE.getState()+"")){
//                entity.setEvaluateItem("已完成");
//            }else{
//                entity.setEvaluateItem("进行中");
//            }
//        }
        return task;
    }

    private Map<String, Object> getDisasterType() {
        Map<String, Object> map = new HashMap<>();
        map.put(DisasterTypeEnum.LANDSLIDE.getState() + "", DisasterTypeEnum.LANDSLIDE.getDesc());
        map.put(DisasterTypeEnum.LIQUEFACTION.getState() + "", DisasterTypeEnum.LIQUEFACTION.getDesc());
        map.put(DisasterTypeEnum.SUBSIDENCE.getState() + "", DisasterTypeEnum.SUBSIDENCE.getDesc());
        return map;
    }

    private Map<String, Object> getStatusMap() {
        Map<String, Object> map = new HashMap<>();
        map.put(TaskEnum.ING.getState() + "", TaskEnum.ING.getDesc());
        map.put(TaskEnum.REVIEWING.getState() + "", TaskEnum.REVIEWING.getDesc());
        map.put(TaskEnum.BACK.getState() + "", TaskEnum.BACK.getDesc());
        map.put(TaskEnum.END.getState() + "", TaskEnum.END.getDesc());
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveTaskDrillVersion(TaskVersion taskVersion) {
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        //softSoilRepository.deleteTaskDrillVersion(taskVersion.getTaskId(),taskVersion.getVersionCode(),taskVersion.getDisasterType());
        taskVersion.setDtcvId(UUIDGenerator.getUUID()).setDisasterType(DisasterTypeEnum.SUBSIDENCE.getState() + "")
                .setCreateUser(userId).setCreateUserName(sUser.getUserName()).setCreateTime(new Date());
        softSoilRepository.saveTaskDrillVersion(taskVersion);
        return taskVersion.getVersionCode();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SoftSoilResult> evaluate(EvaluateVO vo) {
        String dtcvId = vo.getDtcvId();
        //评估之前先删除之前该任务生成的最终结果
        if(PlatformObjectUtils.isNotEmpty(vo.getDtcvId())){
            //要么是最终结果再次评估要么是中间结果再次评估
            softSoilRepository.deleteModelDataById(vo.getDtcvId());
            softSoilRepository.deleteResultDataById(vo.getDtcvId());
            softSoilRepository.deletePolygonEvaluateResult(vo.getDtcvId());
        }else{
            dtcvId =  UUIDGenerator.getUUID();
        }
        String fina = vo.getResultStatus();
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        //创建新的最终结果模型数据
        TaskVersion taskVersion = new TaskVersion();
        taskVersion.setDtcvId(dtcvId).setTaskId(vo.getTaskId()).setVersionCode(vo.getVersionCode())
                .setDisasterType(DisasterTypeEnum.SUBSIDENCE.getState() + "").setCreateUser(userId).setCreateUserName(sUser.getUserName())
                .setCreateTime(new Date()).setDataFrom(vo.getDataFrom()).setEvaluateUser(userId).setEvaluateUserName(sUser.getUserName())
                .setEvaluateTime(new Date()).setResultStatus(fina).setDelFlag(YNEnum.N.toString());
        softSoilRepository.saveTaskModelResult(taskVersion);
        List<SoftSoilResult> softSoilResults = new ArrayList<>();
        //根据标识选择钻孔数据使用用户上传的还是来自基础数据的数据 1：基础数据；2：用户上传的
        if ("1".equals(vo.getDataFrom())) {
            String url = basicDataUrl + "/datacenter/jcRfcpY02/y0206list?dataVersion=" + vo.getVersionCode();
            List<JSONObject> result = (List<JSONObject>) drillService.getJCSJ(url, 3).getData();
            if (PlatformObjectUtils.isNotEmpty(result)) {
                String finalDtcvId = dtcvId;
                result.forEach(json -> {
                    SoftSoilResult entity = JSON.toJavaObject(json, SoftSoilResult.class);
                    entity.setSserId(UUIDGenerator.getUUID());
                    BigDecimal shearWaveVelocity = entity.getShearWaveVelocity();
                    BigDecimal intensity7 = entity.getIntensity7();
                    BigDecimal intensity8 = entity.getIntensity8();
                    BigDecimal intensity9 = entity.getIntensity9();
                    if (shearWaveVelocity.compareTo(intensity7) > 0) {
                        entity.setIsSoft7(0);
                    } else {
                        entity.setIsSoft7(1);
                    }
                    //0 不震陷 1：震陷
                    entity.setIsSoft8(shearWaveVelocity.compareTo(intensity8) > 0 ? 0 : 1);
                    entity.setIsSoft9(shearWaveVelocity.compareTo(intensity9) > 0 ? 0 : 1);
                    entity.setDtcvId(finalDtcvId);
                    entity.setGeom("POINT(" + json.getBigDecimal("longitude") + " " + json.getBigDecimal("latitude") + ")");
                    softSoilRepository.save(entity);
                    if (shearWaveVelocity.compareTo(intensity7) > 0) {
                        entity.setIsSoft7(0);
                    } else {
                        entity.setIsSoft7(1);
                    }
                    entity.setIsSoft8(shearWaveVelocity.compareTo(intensity8) > 0 ? 0 : 1);
                    entity.setIsSoft9(shearWaveVelocity.compareTo(intensity9) > 0 ? 0 : 1);
                    softSoilResults.add(entity);
                });
            }
        } else {//导入钻孔数据
            List<SoftSoilDrill> result = softSoilRepository.getImportDrillData(vo.getTaskId(), vo.getVersionCode());
            if (PlatformObjectUtils.isNotEmpty(result)) {
                String finalDtcvId = dtcvId;
                result.forEach(softSoilDrill -> {
                    SoftSoilResult entity = new SoftSoilResult();
                    entity.setDrillCode(softSoilDrill.getDrillCode());
                    entity.setLongitude(softSoilDrill.getLongitude());
                    entity.setLatitude(softSoilDrill.getLatitude());
                    entity.setGeotechnicalDesignation(softSoilDrill.getGeotechnicalDesignation());
                    entity.setLayerThickness(softSoilDrill.getLayerThickness());
                    entity.setShearWaveVelocity(softSoilDrill.getShearWaveVelocity());
                    entity.setSserId(UUIDGenerator.getUUID());
                    BigDecimal shearWaveVelocity = entity.getShearWaveVelocity();
                    BigDecimal intensity7 = entity.getIntensity7();
                    BigDecimal intensity8 = entity.getIntensity8();
                    BigDecimal intensity9 = entity.getIntensity9();
                    if (shearWaveVelocity.compareTo(intensity7) > 0) {
                        entity.setIsSoft7(0);
                    } else {
                        entity.setIsSoft7(1);
                    }
                    entity.setIsSoft8(shearWaveVelocity.compareTo(intensity8) > 0 ? 0 : 1);
                    entity.setIsSoft9(shearWaveVelocity.compareTo(intensity9) > 0 ? 0 : 1);
                    entity.setDtcvId(finalDtcvId);
                    entity.setGeom("POINT(" + softSoilDrill.getLongitude() + " " + softSoilDrill.getLatitude() + ")");
                    softSoilRepository.save(entity);
                    if (shearWaveVelocity.compareTo(intensity7) > 0) {
                        entity.setIsSoft7(0);
                    } else {
                        entity.setIsSoft7(1);
                    }
                    entity.setIsSoft8(shearWaveVelocity.compareTo(intensity8) > 0 ? 0 : 1);
                    entity.setIsSoft9(shearWaveVelocity.compareTo(intensity9) > 0 ? 0 : 1);
                    softSoilResults.add(entity);
                });
            }
        }

        return softSoilResults;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveToCenterResult(EvaluateVO vo) {
        String userId = PlatformSessionContext.getUserID();
        //根据任务id获取关联的最终结果
        //TaskVersion taskVersion = softSoilRepository.getTaskModelFinalResult(vo.getTaskId(), ResultEnum.FINA.getState() + "");
        TaskVersion taskVersion = softSoilRepository.getTaskModelById(vo.getDtcvId());
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        //保存新的中间版本
        String dtcvId = UUIDGenerator.getUUID();
        TaskVersion version = new TaskVersion();
        BeanUtils.copyProperties(taskVersion, version);
        version.setCreateTime(new Date()).setCreateUser(userId).setCreateUserName(sUser.getUserName()).setDtcvId(dtcvId).setResultStatus(ResultEnum.CENTER.getState() + "");
        softSoilRepository.saveTaskCenterVersion(version);
        //保存中间评估数据
        List<SoftSoilResult> result = softSoilRepository.findDataById(dtcvId);
        if (PlatformObjectUtils.isNotEmpty(result)) {
            result.forEach(entity -> {
                //设置为中间结果 复制一份数据id改变 状态由最终结果设置为中间结果 原有的最终结果不变
                SoftSoilResult copyResult = new SoftSoilResult();
                BeanUtils.copyProperties(entity, copyResult);
                copyResult.setSserId(UUIDGenerator.getUUID());
                copyResult.setDtcvId(dtcvId);
                softSoilRepository.save(copyResult);
            });
        }
    }

    @Override
    public ValuatePage getEvaluatePage(String taskId,String dtcvId) {
        ValuatePage page = new ValuatePage();
        page.setDtcvId(dtcvId);
        TaskEntity taskEntity = taskRepository.viewTask(taskId);
        Map<String, Object> disasterType = this.getDisasterType();
        page.setTaskId(taskEntity.getDtId()).setTaskNum(taskEntity.getTaskNum()).setDisasterType(DisasterTypeEnum.SUBSIDENCE.getDesc())
                .setTaskDistrict(taskEntity.getTaskDistrict());
        //TaskVersion result = softSoilRepository.findDataByTaskId(taskId,"2");
        if(StringUtils.isNotBlank(dtcvId)){
            TaskVersion result = softSoilRepository.getTaskModelById(dtcvId);
            String evaluateUserName = result.getEvaluateUserName();
            page.setEvaluateUserName(evaluateUserName);
            page.setDataFrom(result.getDataFrom());
            List<SoftSoilResult> list = softSoilRepository.findDataById(dtcvId);
            page.setResultList(list);
            page.setVersionCode(result.getVersionCode());//钻孔数据版本号
        }else{
            String userId = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            page.setEvaluateUserName(sUser.getUserName());
            page.setDataFrom("1");
        }
        return page;
    }

    @Override
    public Map<String, Object> getCenterDataPage(String taskId, int curPage, int pageSize) {
        return softSoilRepository.getCenterDataPage(taskId, curPage, pageSize);
    }

    @Override
    public void saveToFinalResult(EvaluateVO vo) {
        String userId = PlatformSessionContext.getUserID();
//        String user = sUserService.getSUser(userId);
//        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String yes = vo.getYes();
        //要转变成最终结果的中间结果
        //TaskVersion taskVersion = softSoilRepository.getTaskModelFinalResult(vo.getTaskId(),"1");
        TaskVersion taskVersion = softSoilRepository.getTaskModelById(vo.getDtcvId());
        //最终结果
        TaskVersion finalResult = softSoilRepository.findDataByTaskId(vo.getTaskId(), "2");
        //将原有的最终结果设置为中间结果
        if ("1".equals(yes)) {
            //将最终结果保存为中间版本
            finalResult.setResultStatus("1").setUpdateUser(userId);
            softSoilRepository.updateTaskModelResult(finalResult);
        } else {
            //将最终结果删除
            softSoilRepository.deleteModelDataById(finalResult.getDtcvId());
            softSoilRepository.deleteResultDataById(finalResult.getDtcvId());
            softSoilRepository.deletePolygonEvaluateResult(finalResult.getDtcvId());
        }
        taskVersion.setResultStatus("2").setUpdateUser(userId);
        softSoilRepository.updateTaskModelResult(taskVersion);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCenterVersion(Map<String, String> map) {
        String dtcvId = map.get("dtcvId");
        softSoilRepository.deleteModelDataById(dtcvId);
        softSoilRepository.deleteResultDataById(dtcvId);
        softSoilRepository.deletePolygonEvaluateResult(dtcvId);
    }

    @Override
    public RestResponse importDrillData(String taskId, String versionCode, MultipartFile file, HttpServletResponse response) {
        String userId = PlatformSessionContext.getUserID();
        TaskEntity taskEntity = taskRepository.viewTask(taskId);
        String geom = taskEntity.getGeom();
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(false);
            // 获取到Excel数据
            ExcelImportResult<SoftSoilDrill> result = ExcelImportUtil.importExcelMore(file.getInputStream(), SoftSoilDrill.class, params);
            List<SoftSoilDrill> list = new ArrayList<>();
            StringBuilder stringBuilder = new StringBuilder("");
            if (StringUtils.isBlank(versionCode) || "0".equals(versionCode)) {
                versionCode = IdUtil.getSnowflakeNextIdStr();
            } else {
                softSoilRepository.delete(taskId, versionCode);
            }
            if (PlatformObjectUtils.isNotEmpty(result.getList())) {
                for (int i = 0; i < result.getList().size(); i++) {
                    SoftSoilDrill softSoilDrill = result.getList().get(i);
                    if (CheckObjFields.isAllFieldNull(softSoilDrill)) {
                        continue;
                    }
                    int count = 0;
                    if (PlatformObjectUtils.isEmpty(softSoilDrill.getDrillCode())) {
                        stringBuilder.append("第" + (i + 1) + "行的钻孔编号不能为空。");
                        count++;
                    }
                    if (PlatformObjectUtils.isEmpty(softSoilDrill.getLongitude())) {
                        stringBuilder.append("第" + (i + 1) + "行的钻孔经度不能为空。");
                        count++;
                    }
                    if (PlatformObjectUtils.isEmpty(softSoilDrill.getLatitude())) {
                        stringBuilder.append("第" + (i + 1) + "行的钻孔纬度不能为空。");
                        count++;
                    }
                    if (PlatformObjectUtils.isEmpty(softSoilDrill.getGeotechnicalDesignation())) {
                        stringBuilder.append("第" + (i + 1) + "行的土层名称不能为空。");
                        count++;
                    }
                    if (PlatformObjectUtils.isEmpty(softSoilDrill.getLayerThickness())) {
                        stringBuilder.append("第" + (i + 1) + "行的土层厚度不能为空。");
                        count++;
                    }
                    if (PlatformObjectUtils.isEmpty(softSoilDrill.getShearWaveVelocity())) {
                        stringBuilder.append("第" + (i + 1) + "行的等效剪切波速不能为空。");
                        count++;
                    }
                    if (count > 0 && count < 6) {
                        break;
                    } else if (count == 6) {
                        stringBuilder = new StringBuilder("");
                        list.remove(i);
                        break;
                    }
                    softSoilDrill.setDssdId(UUIDGenerator.getUUID());
                    softSoilDrill.setTaskId(taskId);
                    softSoilDrill.setCreateUser(userId);
                    softSoilDrill.setCreateTime(new Date());
                    softSoilDrill.setVersionCode(versionCode);
                    Boolean stIntersects = lawAnalysisRepository.getSTIntersects(geom, softSoilDrill.getLongitude(), softSoilDrill.getLatitude());
                    if(!stIntersects){
                        stringBuilder.append("第").append(i + 1).append("行钻孔不在任务范围内。");
                    }else{
                        list.add(softSoilDrill);
                    }
                }
            }
            if (stringBuilder.length() == 0 && list.size() > 0) {
                int i = softSoilRepository.importDrillData(list);
                System.out.println("插入条数：" + i);
            }
            return stringBuilder.length() > 0 ? RestResponse.fail(stringBuilder.toString()) :
                    RestResponse.succeed(versionCode);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail("导入失败，请检查数据正确性");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePolygonEvaluateResult(List<PolygonEvaluateResultVO> voList) {
        PolygonEvaluateResultVO polygonEvaluateResultVO = voList.get(0);
        //先删除
        softSoilRepository.deleteByDtcvId(polygonEvaluateResultVO.getDtcvId());
        String taskName = softSoilRepository.getTaskName(polygonEvaluateResultVO.getDtcvId());
        String flag = "0";
        if(taskName.contains("大屏展示")){
            flag = "1";
        }
        for(PolygonEvaluateResultVO entity:voList){
            entity.setDssperId(UUIDGenerator.getUUID());
            entity.setFlag(flag);
        };
        softSoilRepository.batchSave(voList);
    }

    //按省统计危险性面积（【软土震陷】分析评估结果）
    @Override
    public RestResponse countResultAreaByProvince(String taskId) {
        if (PlatformObjectUtils.isEmpty(taskId)) {
            return RestResponse.fail("按省统计危险性面积失败！");
        }
        String modelType = "软土震陷";//模型类型
        String countType = "0";//按省统计
        //根据任务id获取关联的最终结果
        TaskVersion taskVersion = softSoilRepository.getTaskModelFinalResult(taskId, ResultEnum.FINA.getState() + "");
        String dtcvId = taskVersion.getDtcvId();
        if (PlatformObjectUtils.isEmpty(dtcvId)) {
            return RestResponse.fail("无软土震陷最终结果数据！");
        }
        String districtLayerName = "district_boundary_province";//省行政区划表
        //任务ID删除统计危险性面积结果
        eqLandslideService.deleteDzzhCountAreaResultByTaskId(taskId,countType,dtcvId);
        List<String> provinceList = new ArrayList<>();
        String sqlFilter = "";
        //查询任务区域
        String sql01 = "select task_district,task_name from dzzh_task where dt_id=?";
        TaskEntity taskEntity = jdbcTemplate.queryForObject(sql01, new BeanPropertyRowMapper<>(TaskEntity.class), taskId);
        String taskDistrict = taskEntity.getTaskDistrict();
        //大屏任务标识1：是大屏任务；0：不是大屏任务
        String dpFlag = "0";
        String taskName = taskEntity.getTaskName();
        if(taskName.contains("大屏展示")){
            dpFlag = "1";
        }
        String[] tempArr = taskDistrict.split(",");
        for(int i=0;i<tempArr.length;i++){
            if (PlatformObjectUtils.isNotEmpty(tempArr[i])) {
                String province = tempArr[i].split("-")[0];
                provinceList.add(province);
                if(i>0){
                    sqlFilter += " or ";
                }
                sqlFilter += "b.name='"+province+"'";
            }
        }
        //烈度7-9
        for (int i = 7; i <=9; i++) {
            String intensity = String.valueOf(i);//烈度
            //根据任务ID获取投影坐标EPSG
            int epsg = elevationMapService.getEPSGFromTask(taskId);
            //计算危险区面积、总面积、占比
            String sql2 = "select *,t.area/t.total_area*100 as percent from " +
                    "(SELECT b.code,b.name,a.value as gridvalue,st_area(st_transform(st_intersection(a.geom, b.geom),"+epsg+"))/1000000 as area," +
                    "st_area(st_transform(b.geom,"+epsg+"))/1000000 as total_area " +
                    "FROM dzzh_soft_soil_polygon_evaluate_result a,"+districtLayerName+" b " +
                    "where a.dtcv_id='"+dtcvId+"' and a.type='"+intensity+"' and "+sqlFilter+" " +
                    "order by b.code,b.name,a.value) t";
            List<DzzhCountAreaResult> dzzhCountAreaResultList = jdbcTemplate.query(sql2,new BeanPropertyRowMapper<>(DzzhCountAreaResult.class));
            for(int m=0;m<dzzhCountAreaResultList.size();m++){
                DzzhCountAreaResult dzzhCountAreaResult = dzzhCountAreaResultList.get(m);
                String uuid = UUIDGenerator.getUUID();
                dzzhCountAreaResult.setId(uuid);
                dzzhCountAreaResult.setTaskId(taskId);
                dzzhCountAreaResult.setModelType(modelType);//模型类型
                dzzhCountAreaResult.setDpFlag(dpFlag);//大屏任务标识1：是大屏任务；0：不是大屏任务
                dzzhCountAreaResult.setDzIntensity(intensity);//地震烈度7-9
//                dzzhCountAreaResult.setLayerName("");//图层名称
                dzzhCountAreaResult.setType(countType);//统计方式：0省 1市
                dzzhCountAreaResult.setModelId(dtcvId);//模型ID
            }
            //保存统计危险性面积结果
            eqLandslideService.saveDzzhCountAreaResultList(dzzhCountAreaResultList);
        }

        return RestResponse.succeed(null);
    }

    //按市统计危险性面积（【软土震陷】分析评估结果）
    @Override
    public RestResponse countResultAreaByCity(String taskId) {
        if (PlatformObjectUtils.isEmpty(taskId)) {
            return RestResponse.fail("按市统计危险性面积失败！");
        }
        String modelType = "软土震陷";//模型类型
        String countType = "1";//按市统计
        //根据任务id获取关联的最终结果
        TaskVersion taskVersion = softSoilRepository.getTaskModelFinalResult(taskId, ResultEnum.FINA.getState() + "");
        String dtcvId = taskVersion.getDtcvId();
        if (PlatformObjectUtils.isEmpty(dtcvId)) {
            return RestResponse.fail("无软土震陷最终结果数据！");
        }
        String districtLayerName = "district_boundary_city";//市行政区划表
        //任务ID删除统计危险性面积结果
        eqLandslideService.deleteDzzhCountAreaResultByTaskId(taskId,countType,dtcvId);
        String sqlFilter = "";
        //查询任务区域
        String sql01 = "select task_district,task_name from dzzh_task where dt_id=?";
        TaskEntity taskEntity = jdbcTemplate.queryForObject(sql01, new BeanPropertyRowMapper<>(TaskEntity.class), taskId);
        String taskDistrict = taskEntity.getTaskDistrict();
        //大屏任务标识1：是大屏任务；0：不是大屏任务
        String dpFlag = "0";
        String taskName = taskEntity.getTaskName();
        if(taskName.contains("大屏展示")){
            dpFlag = "1";
        }
        String[] tempArr = taskDistrict.split(",");
        List<String> provinceList = new ArrayList<>();
        for(int i=0;i<tempArr.length;i++){
            String[] tempStrArr = tempArr[i].split("-");
            if(tempStrArr.length>1){
                String city = tempStrArr[1];
                if(i>0){
                    sqlFilter += " or ";
                }
                sqlFilter += "b.name='"+city+"'";
            }else{
                String province = tempStrArr[0];
                if (PlatformObjectUtils.isNotEmpty(province)) {
                    provinceList.add(province);
                }
            }
        }
        if(provinceList.size()>0){//应获取全省的市
            String provinceStr = "";
            for(int i=0;i<provinceList.size();i++){
                String province = provinceList.get(i);
                if(i>0){
                    provinceStr += ",";
                }
                provinceStr += "'"+province+"'";
            }
            //查询省行政区划编码前2位
            String sql = "select subString(code,1,2) as code from district_boundary_province where name in ("+provinceStr+")";
            List<String> codeList = jdbcTemplate.queryForList(sql,String.class);
            if (codeList!=null && codeList.size()>0) {
                if (PlatformObjectUtils.isNotEmpty(sqlFilter)) {
                    sqlFilter += " and ";
                }
                sqlFilter += "(";
                for(int i=0;i<codeList.size();i++){
                    String code = codeList.get(i);//行政区划编码前2位
                    if(i>0){
                        sqlFilter += " or ";
                    }
                    sqlFilter += "b.code like '"+code+"%'";
                }
                sqlFilter += ")";
            }
        }
        //烈度7-9
        for (int i = 7; i <=9; i++) {
            String intensity = String.valueOf(i);//烈度
            //根据任务ID获取投影坐标EPSG
            int epsg = elevationMapService.getEPSGFromTask(taskId);
            //计算危险区面积、总面积、占比
            String sql2 = "select *,t.area/t.total_area*100 as percent from " +
                    "(SELECT b.code,b.name,a.value as gridvalue,st_area(st_transform(st_intersection(a.geom, b.geom),"+epsg+"))/1000000 as area," +
                    "st_area(st_transform(b.geom,"+epsg+"))/1000000 as total_area " +
                    "FROM dzzh_soft_soil_polygon_evaluate_result a,"+districtLayerName+" b " +
                    "where a.dtcv_id='"+dtcvId+"' and a.type='"+intensity+"'  and "+sqlFilter+" " +
                    "order by b.code,b.name,a.value) t";
            List<DzzhCountAreaResult> dzzhCountAreaResultList = jdbcTemplate.query(sql2,new BeanPropertyRowMapper<>(DzzhCountAreaResult.class));
            for(int m=0;m<dzzhCountAreaResultList.size();m++){
                DzzhCountAreaResult dzzhCountAreaResult = dzzhCountAreaResultList.get(m);
                String uuid = UUIDGenerator.getUUID();
                dzzhCountAreaResult.setId(uuid);
                dzzhCountAreaResult.setTaskId(taskId);
                dzzhCountAreaResult.setModelType(modelType);//模型类型
                dzzhCountAreaResult.setDpFlag(dpFlag);//大屏任务标识1：是大屏任务；0：不是大屏任务
                dzzhCountAreaResult.setDzIntensity(intensity);//地震烈度7-9
//                dzzhCountAreaResult.setLayerName("");//图层名称
                dzzhCountAreaResult.setType(countType);//统计方式：0省 1市
                dzzhCountAreaResult.setModelId(dtcvId);//模型ID
            }
            //保存统计危险性面积结果
            eqLandslideService.saveDzzhCountAreaResultList(dzzhCountAreaResultList);
        }

        return RestResponse.succeed(null);
    }

    @Override
    public RestResponse countResultAreaByCounty(String taskId) {
        if (PlatformObjectUtils.isEmpty(taskId)) {
            return RestResponse.fail("按区县统计危险性面积失败！");
        }
        String modelType = "软土震陷";//模型类型
        String countType = "2";//按市统计
        //根据任务id获取关联的最终结果
        TaskVersion taskVersion = softSoilRepository.getTaskModelFinalResult(taskId, ResultEnum.FINA.getState() + "");
        String dtcvId = taskVersion.getDtcvId();
        if (PlatformObjectUtils.isEmpty(dtcvId)) {
            return RestResponse.fail("无软土震陷最终结果数据！");
        }
        String districtLayerName = "district_boundary_county";//市行政区划表
        //任务ID删除统计危险性面积结果
        eqLandslideService.deleteDzzhCountAreaResultByTaskId(taskId,countType,dtcvId);
        String sqlFilter = "";
        //查询任务区域
        String sql01 = "select task_district,task_name from dzzh_task where dt_id=?";
        TaskEntity taskEntity = jdbcTemplate.queryForObject(sql01, new BeanPropertyRowMapper<>(TaskEntity.class), taskId);
        String taskDistrict = taskEntity.getTaskDistrict();
        //大屏任务标识1：是大屏任务；0：不是大屏任务
        String dpFlag = "0";
        String taskName = taskEntity.getTaskName();
        if(taskName.contains("大屏展示")){
            dpFlag = "1";
        }
        String[] tempArr = taskDistrict.split(",");
        List<String> provinceList = new ArrayList<>();
        List<String> cityList = new ArrayList<>();
        for(int i=0;i<tempArr.length;i++){
            String[] tempStrArr = tempArr[i].split("-");
            if(tempStrArr.length>2){
                String city = tempStrArr[2];
                if(i>0){
                    sqlFilter += " or ";
                }
                sqlFilter += "b.name='"+city+"'";
            }else if(tempStrArr.length>1){
                String city = tempStrArr[1];
                if (PlatformObjectUtils.isNotEmpty(city)) {
                    cityList.add(tempStrArr[0]+"_"+city);
                }
            }else{
                String province = tempStrArr[0];
                if (PlatformObjectUtils.isNotEmpty(province)) {
                    provinceList.add(province);
                }
            }
        }
        if(cityList.size()>0){
            //获取每个市的区县
            String sql = "select subString(code,1,4) as code from district_boundary_city where 1=1 ";
            int i = 0;
            for (; i < cityList.size(); i++) {
                String area = cityList.get(i);
                //查询省code的前两位
                String subSql = "select subString(code,1,2) as code from district_boundary_province where name = '"+area.split("_")[0]+"'";
                List<String> codeList = jdbcTemplate.queryForList(subSql, String.class);
                String provinceCode = "";
                if (PlatformObjectUtils.isNotEmpty(codeList) && codeList.size() > 0) {
                    provinceCode = codeList.get(0);
                }
                if (i > 0) {
                    sql += " or ";
                }
                if(StringUtils.isNotBlank(provinceCode)){
                    sql+=" and  (name='"+area.split("_")[1]+"' and code like '" + provinceCode + "%')";
                }else{
                    sql+=" and  (name='"+area.split("_")[1]+"')";
                }
            }
            if(i>0){
                //市code
                List<String> codeList = jdbcTemplate.queryForList(sql, String.class);
                if (PlatformObjectUtils.isNotEmpty(codeList) && codeList.size() > 0) {
                    if (PlatformObjectUtils.isNotEmpty(sqlFilter)) {
                        sqlFilter += " and ";
                    }
                    sqlFilter += "(";
                    for(int j=0;j<codeList.size();j++){
                        String code = codeList.get(j);//行政区划编码前2位
                        if(j>0){
                            sqlFilter += " or ";
                        }
                        sqlFilter += "b.code like '"+code+"%'";
                    }
                    sqlFilter += ")";
                }
            }
        }
        if(provinceList.size()>0){//应获取全省的市
            String provinceStr = "";
            for(int i=0;i<provinceList.size();i++){
                String province = provinceList.get(i);
                if(i>0){
                    provinceStr += ",";
                }
                provinceStr += "'"+province+"'";
            }
            //查询省行政区划编码前2位
            String sql = "select subString(code,1,2) as code from district_boundary_province where name in ("+provinceStr+")";
            List<String> codeList = jdbcTemplate.queryForList(sql,String.class);
            if (codeList!=null && codeList.size()>0) {
                if (PlatformObjectUtils.isNotEmpty(sqlFilter)) {
                    sqlFilter += " and ";
                }
                sqlFilter += "(";
                for(int i=0;i<codeList.size();i++){
                    String code = codeList.get(i);//行政区划编码前2位
                    if(i>0){
                        sqlFilter += " or ";
                    }
                    sqlFilter += "b.code like '"+code+"%'";
                }
                sqlFilter += ")";
            }
        }
        //烈度7-9
        for (int i = 7; i <=9; i++) {
            String intensity = String.valueOf(i);//烈度
            //根据任务ID获取投影坐标EPSG
            int epsg = elevationMapService.getEPSGFromTask(taskId);
            //计算危险区面积、总面积、占比
            String sql2 = "select *,t.area/t.total_area*100 as percent from " +
                    "(SELECT b.code,b.name,a.value as gridvalue,st_area(st_transform(st_intersection(a.geom, b.geom),"+epsg+"))/1000000 as area," +
                    "st_area(st_transform(b.geom,"+epsg+"))/1000000 as total_area " +
                    "FROM dzzh_soft_soil_polygon_evaluate_result a,"+districtLayerName+" b " +
                    "where a.dtcv_id='"+dtcvId+"' and a.type='"+intensity+"'  and "+sqlFilter+" " +
                    "order by b.code,b.name,a.value) t";
            List<DzzhCountAreaResult> dzzhCountAreaResultList = jdbcTemplate.query(sql2,new BeanPropertyRowMapper<>(DzzhCountAreaResult.class));
            for(int m=0;m<dzzhCountAreaResultList.size();m++){
                DzzhCountAreaResult dzzhCountAreaResult = dzzhCountAreaResultList.get(m);
                String uuid = UUIDGenerator.getUUID();
                dzzhCountAreaResult.setId(uuid);
                dzzhCountAreaResult.setTaskId(taskId);
                dzzhCountAreaResult.setModelType(modelType);//模型类型
                dzzhCountAreaResult.setDpFlag(dpFlag);//大屏任务标识1：是大屏任务；0：不是大屏任务
                dzzhCountAreaResult.setDzIntensity(intensity);//地震烈度7-9
//                dzzhCountAreaResult.setLayerName("");//图层名称
                dzzhCountAreaResult.setType(countType);//统计方式：0省 1市
                dzzhCountAreaResult.setModelId(dtcvId);//模型ID
            }
            //保存统计危险性面积结果
            eqLandslideService.saveDzzhCountAreaResultList(dzzhCountAreaResultList);
        }

        return RestResponse.succeed(null);
    }

    @Override
    public JSONObject getCountAreaResult() {
        JSONObject  js = new JSONObject();
        List<CountAreaResult> list = eqLandslideService.getCountAreaResult();
        js.put("result",PlatformObjectUtils.isNotEmpty(list) && list.size()>0?list:new ArrayList<>());
        return js;
    }
}
